import { 
  AmbientLight,
  Font,
  FontLoader,
  Group,
  Mesh,
  MeshPhongMaterial,
  PerspectiveCamera, 
  Scene, 
  SpotLight, 
  TextGeometry, 
  TextGeometryParameters, 
  WebGLRenderer
} from "three"
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'
import stats from "../utils/stats"

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(-20, 12, 400)
camera.lookAt(0, 0, 0)

const renderer = new WebGLRenderer({ antialias: true })
renderer.setClearColor(0x000000)
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = {
  font: null,
  size: 30,
  height: 30
}

let group = new Group()
// 外部导入
const fontload1 = new FontLoader()
fontload1.load(
  // 资源
  '/fonts/helvetiker_regular.typeface.json', 
  // 加载完成时
  res => {
    controls.font = res

    let mesh = drawFont(res)
    group.add(mesh)
  },
  // 加载进度 
  xhr => {
    console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
  }, 
  err => {
    console.error(err)
  }
)

scene.add(group)

const ambient = new AmbientLight(0x0c0c0c)
scene.add(ambient)

const spotlight = new SpotLight(0xffffff)
spotlight.position.set(100, 100, 100)
scene.add(spotlight)
// scene.add(new SpotLightHelper(spotlight))

const trackballControls = new TrackballControls(camera, renderer.domElement)

function render() {
  stats.update()
  trackballControls.update()

  group.rotation.y += 0.01
  group.rotation.x += 0.01

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}
render()

function drawFont(font: Font): Mesh {
  const fontOptins: TextGeometryParameters = {
    font,
    size: controls.size,
  }
  const material = new MeshPhongMaterial({
    color: 0xff9900
  })
  const textGeom = new TextGeometry('Hello World', fontOptins)
  return new Mesh(textGeom.center(), material)
}